<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>集成演示应用 - 客户管理、产品管理和订阅功能</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f8fafc;
            color: #1a202c;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            text-align: center;
        }

        .header h1 {
            color: #2d3748;
            margin-bottom: 10px;
        }

        .header p {
            color: #718096;
        }

        .tabs {
            display: flex;
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .tab {
            flex: 1;
            padding: 16px 24px;
            background: #f7fafc;
            border: none;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            color: #4a5568;
            transition: all 0.2s;
        }

        .tab.active {
            background: #2d3748;
            color: white;
        }

        .tab:hover:not(.active) {
            background: #e2e8f0;
        }

        .tab-content {
            display: none;
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #2d3748;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.2s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #2d3748;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: #2d3748;
            color: white;
        }

        .btn-primary:hover {
            background: #1a202c;
        }

        .btn-secondary {
            background: #e2e8f0;
            color: #2d3748;
        }

        .btn-secondary:hover {
            background: #cbd5e0;
        }

        .btn-success {
            background: #48bb78;
            color: white;
        }

        .btn-success:hover {
            background: #38a169;
        }

        .btn-danger {
            background: #e53e3e;
            color: white;
        }

        .btn-danger:hover {
            background: #c53030;
        }

        .status-message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            font-weight: 500;
        }

        .status-success {
            background: #c6f6d5;
            color: #22543d;
            border: 1px solid #9ae6b4;
        }

        .status-error {
            background: #fed7d7;
            color: #742a2a;
            border: 1px solid #feb2b2;
        }

        .status-info {
            background: #bee3f8;
            color: #2a4365;
            border: 1px solid #90cdf4;
        }

        .card {
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }

        .card h3 {
            color: #2d3748;
            margin-bottom: 12px;
        }

        .card-content {
            color: #4a5568;
        }

        .card-actions {
            margin-top: 12px;
            display: flex;
            gap: 8px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #718096;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #2d3748;
            margin-bottom: 8px;
        }

        .stat-label {
            color: #718096;
            font-size: 14px;
        }

        .subscription-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
        }

        .status-active {
            background: #c6f6d5;
            color: #22543d;
        }

        .status-past_due {
            background: #fed7d7;
            color: #742a2a;
        }

        .status-canceled {
            background: #e2e8f0;
            color: #4a5568;
        }

        .status-canceling {
            background: #fef5e7;
            color: #744210;
        }

        .cancellation-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            margin-left: 8px;
            background: #fed7d7;
            color: #742a2a;
            border: 1px solid #feb2b2;
        }

        .price-display {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .tabs {
                flex-direction: column;
            }
            
            .stats {
                grid-template-columns: 1fr;
            }
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            color: #2d3748;
        }

        .close {
            color: #718096;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover {
            color: #2d3748;
        }

        .modal-body {
            padding: 24px;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <h1>🎯 集成演示应用</h1>
            <p>客户管理、产品管理和订阅功能</p>
        </div>

        <!-- 统计信息 -->
        <div class="stats">
            <div class="stat-card">
                <div class="stat-number" id="customerCount">0</div>
                <div class="stat-label">客户总数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="productCount">0</div>
                <div class="stat-label">产品总数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="subscriptionCount">0</div>
                <div class="stat-label">订阅总数</div>
            </div>
        </div>

        <!-- 标签页 -->
        <div class="tabs">
            <button class="tab active" onclick="showTab('customers')">👥 客户管理</button>
            <button class="tab" onclick="showTab('products')">📦 产品管理</button>
            <button class="tab" onclick="showTab('subscriptions')">💳 订阅管理</button>
            <button class="tab" onclick="showTab('portal')">🌐 Customer Portal</button>
        </div>

        <!-- 状态消息 -->
        <div id="statusMessage" style="display: none;"></div>

        <!-- 客户管理 -->
        <div id="customers" class="tab-content active">
            <h2>👥 客户管理</h2>
            
            <!-- 创建客户表单 -->
            <div class="card">
                <h3>创建新客户</h3>
                <form id="customerForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="customerEmail">邮箱 *</label>
                            <input type="email" id="customerEmail" required placeholder="customer@example.com">
                        </div>
                        <div class="form-group">
                            <label for="customerName">姓名</label>
                            <input type="text" id="customerName" placeholder="客户姓名">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="customerPhone">电话</label>
                        <input type="tel" id="customerPhone" placeholder="+1234567890">
                    </div>
                    <button type="submit" class="btn btn-primary">创建客户</button>
                </form>
            </div>

            <!-- 客户列表 -->
            <div class="card">
                <h3>客户列表</h3>
                <div id="customersList">
                    <div class="loading">加载客户列表...</div>
                </div>
            </div>
        </div>

        <!-- 产品管理 -->
        <div id="products" class="tab-content">
            <h2>📦 产品管理</h2>
            
            <!-- 创建产品表单 -->
            <div class="card">
                <h3>创建新产品</h3>
                <form id="productForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="productName">产品名称 *</label>
                            <input type="text" id="productName" required placeholder="产品名称">
                        </div>
                        <div class="form-group">
                            <label for="productAmount">价格（分） *</label>
                            <input type="number" id="productAmount" required placeholder="1000" min="1">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="productDescription">产品描述</label>
                        <textarea id="productDescription" rows="3" placeholder="产品详细描述"></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="productCurrency">货币</label>
                            <select id="productCurrency">
                                <option value="usd">USD</option>
                                <option value="eur">EUR</option>
                                <option value="cny">CNY</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="productInterval">订阅周期</label>
                            <select id="productInterval">
                                <option value="month">月付</option>
                                <option value="year">年付</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">创建产品</button>
                </form>
            </div>

            <!-- 产品列表 -->
            <div class="card">
                <h3>产品列表</h3>
                <div id="productsList">
                    <div class="loading">加载产品列表...</div>
                </div>
            </div>
        </div>

        <!-- 订阅管理 -->
        <div id="subscriptions" class="tab-content">
            <h2>💳 订阅管理</h2>
            
            <!-- 创建订阅表单 -->
            <div class="card">
                <h3>创建订阅</h3>
                <form id="subscriptionForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="subscriptionCustomer">选择客户 *</label>
                            <select id="subscriptionCustomer" required>
                                <option value="">请选择客户</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="subscriptionProduct">选择产品 *</label>
                            <select id="subscriptionProduct" required>
                                <option value="">请选择产品</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <button type="submit" class="btn btn-primary">创建订阅</button>
                        <button type="button" onclick="createSubscriptionWithPayment()" class="btn btn-success">订阅支付</button>
                    </div>
                </form>
            </div>

            <!-- 订阅列表 -->
            <div class="card">
                <h3>订阅列表</h3>
                <div id="subscriptionsList">
                    <div class="loading">加载订阅列表...</div>
                </div>
            </div>
        </div>

        <!-- Customer Portal -->
        <div id="portal" class="tab-content">
            <h2>🌐 Customer Portal</h2>
            
            <div class="card">
                <h3>客户订阅管理</h3>
                <p>为客户提供完整的订阅管理界面，包括查看订阅状态、管理支付方式、查看账单历史等。</p>
                
                <div class="form-group">
                    <label for="portalCustomer">选择客户</label>
                    <select id="portalCustomer">
                        <option value="">请选择客户</option>
                    </select>
                </div>
                
                <button onclick="openCustomerPortal()" class="btn btn-success">打开 Customer Portal</button>
            </div>
        </div>
    </div>

    <!-- 升级/降级订阅模态框 -->
    <div id="upgradeModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>升级/降级订阅</h3>
                <span class="close" onclick="closeUpgradeModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="upgradeForm">
                    <div class="form-group">
                        <label for="upgradeProduct">选择新产品 *</label>
                        <select id="upgradeProduct" required>
                            <option value="">请选择产品</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="prorationBehavior">差价处理方式</label>
                        <select id="prorationBehavior">
                            <option value="create_prorations">创建按比例收费</option>
                            <option value="none">不处理差价</option>
                            <option value="always_invoice">总是创建发票</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="billingCycleAnchor">计费周期锚点</label>
                        <select id="billingCycleAnchor">
                            <option value="now">立即生效</option>
                            <option value="unchanged">保持原周期</option>
                        </select>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">确认升级/降级</button>
                        <button type="button" onclick="closeUpgradeModal()" class="btn btn-secondary">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        const API_BASE_URL = "http://localhost:8003/api";
        let customers = [];
        let products = [];
        let subscriptions = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadAllData();
            setupEventListeners();
        });

        // 设置事件监听器
        function setupEventListeners() {
            // 客户表单
            document.getElementById('customerForm').addEventListener('submit', createCustomer);
            
            // 产品表单
            document.getElementById('productForm').addEventListener('submit', createProduct);
            
            // 订阅表单
            document.getElementById('subscriptionForm').addEventListener('submit', createSubscription);
            
            // 升级/降级表单
            document.getElementById('upgradeForm').addEventListener('submit', handleUpgradeSubmit);
        }

        // 显示标签页
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签页的active类
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            
            // 添加active类到选中的标签
            event.target.classList.add('active');
        }

        // 显示状态消息
        function showStatus(type, message) {
            const statusDiv = document.getElementById('statusMessage');
            statusDiv.className = `status-message status-${type}`;
            statusDiv.textContent = message;
            statusDiv.style.display = 'block';
            
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }

        // 加载所有数据
        async function loadAllData() {
            try {
                await Promise.all([
                    loadCustomers(),
                    loadProducts(),
                    loadSubscriptions()
                ]);
                updateStats();
            } catch (error) {
                console.error('加载数据失败:', error);
                showStatus('error', '加载数据失败');
            }
        }

        // 加载客户列表
        async function loadCustomers() {
            try {
                // 添加时间戳参数防止缓存
                const timestamp = new Date().getTime();
                const response = await fetch(`${API_BASE_URL}/customers?t=${timestamp}`, {
                    headers: {
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache'
                    }
                });
                const data = await response.json();
                
                if (response.ok) {
                    customers = data; // 后端直接返回数组
                    displayCustomers();
                    updateCustomerSelects();
                } else {
                    throw new Error(data.detail || '获取客户列表失败');
                }
            } catch (error) {
                console.error('加载客户失败:', error);
                showStatus('error', '加载客户列表失败');
            }
        }

        // 显示客户列表
        function displayCustomers() {
            const container = document.getElementById('customersList');
            
            if (!customers || customers.length === 0) {
                container.innerHTML = '<p>暂无客户</p>';
                return;
            }

            let html = '';
            customers.forEach(customer => {
                html += `
                    <div class="card">
                        <div class="card-content">
                            <strong>${customer.name || '未命名'}</strong><br>
                            邮箱: ${customer.email}<br>
                            电话: ${customer.phone || '未提供'}<br>
                            创建时间: ${new Date(customer.created_at).toLocaleString()}
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 创建客户
        async function createCustomer(e) {
            e.preventDefault();
            
            const email = document.getElementById('customerEmail').value;
            const name = document.getElementById('customerName').value;
            const phone = document.getElementById('customerPhone').value;
            
            try {
                const response = await fetch(`${API_BASE_URL}/customers`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        email: email,
                        name: name || null,
                        phone: phone || null
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', `客户创建成功: ${result.email}`);
                    document.getElementById('customerForm').reset();
                    await loadCustomers();
                } else {
                    throw new Error(result.detail || '创建客户失败');
                }
            } catch (error) {
                console.error('创建客户失败:', error);
                showStatus('error', `创建客户失败: ${error.message}`);
            }
        }

        // 加载产品列表
        async function loadProducts() {
            try {
                // 添加时间戳参数防止缓存
                const timestamp = new Date().getTime();
                const response = await fetch(`${API_BASE_URL}/products?t=${timestamp}`, {
                    headers: {
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache'
                    }
                });
                const data = await response.json();
                
                if (response.ok) {
                    products = data; // 后端直接返回数组
                    displayProducts();
                    updateProductSelects();
                } else {
                    throw new Error(data.detail || '获取产品列表失败');
                }
            } catch (error) {
                console.error('加载产品失败:', error);
                showStatus('error', '加载产品列表失败');
            }
        }

        // 显示产品列表
        function displayProducts() {
            const container = document.getElementById('productsList');
            
            if (!products || products.length === 0) {
                container.innerHTML = '<p>暂无产品</p>';
                return;
            }

            let html = '';
            products.forEach(product => {
                const price = (product.unit_amount / 100).toFixed(2);
                const interval = product.interval === 'month' ? '月' : '年';
                
                html += `
                    <div class="card">
                        <div class="card-content">
                            <strong>${product.name}</strong><br>
                            描述: ${product.description || '无描述'}<br>
                            价格: ${price} ${product.currency.toUpperCase()} / ${interval}<br>
                            价格ID: ${product.stripe_price_id}<br>
                            创建时间: ${new Date(product.created_at).toLocaleString()}
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 创建产品
        async function createProduct(e) {
            e.preventDefault();
            
            const name = document.getElementById('productName').value;
            const description = document.getElementById('productDescription').value;
            const amount = parseInt(document.getElementById('productAmount').value);
            const currency = document.getElementById('productCurrency').value;
            const interval = document.getElementById('productInterval').value;
            
            try {
                const response = await fetch(`${API_BASE_URL}/products`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: name,
                        description: description || null,
                        unit_amount: amount,
                        currency: currency,
                        interval: interval,
                        interval_count: 1
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', `产品创建成功: ${result.name}`);
                    document.getElementById('productForm').reset();
                    await loadProducts();
                } else {
                    throw new Error(result.detail || '创建产品失败');
                }
            } catch (error) {
                console.error('创建产品失败:', error);
                showStatus('error', `创建产品失败: ${error.message}`);
            }
        }

        // 加载订阅列表
        async function loadSubscriptions() {
            try {
                // 添加时间戳参数防止缓存
                const timestamp = new Date().getTime();
                const response = await fetch(`${API_BASE_URL}/subscriptions?t=${timestamp}`, {
                    headers: {
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache'
                    }
                });
                const data = await response.json();
                
                if (response.ok) {
                    subscriptions = data; // 后端直接返回数组
                    displaySubscriptions();
                    console.log('订阅数据已刷新，当前订阅数量:', subscriptions.length);
                } else {
                    throw new Error(data.detail || '获取订阅列表失败');
                }
            } catch (error) {
                console.error('加载订阅失败:', error);
                showStatus('error', '加载订阅列表失败');
            }
        }

        // 显示订阅列表
        function displaySubscriptions() {
            const container = document.getElementById('subscriptionsList');
            
            if (!subscriptions || subscriptions.length === 0) {
                container.innerHTML = '<p>暂无订阅</p>';
                return;
            }

            let html = '';
            subscriptions.forEach(subscription => {
                const startDate = new Date(subscription.current_period_start * 1000).toLocaleDateString();
                const endDate = new Date(subscription.current_period_end * 1000).toLocaleDateString();
                
                // 查找对应的产品和客户信息
                const product = products.find(p => p.id === subscription.product_id);
                const customer = customers.find(c => c.id === subscription.customer_id);
                
                // 处理订阅状态显示
                let statusDisplay = subscription.status;
                let statusClass = `status-${subscription.status}`;
                
                // 添加取消状态指示器（不影响原状态显示）
                let cancellationIndicator = '';
                if (subscription.cancel_at_period_end) {
                    cancellationIndicator = '<span class="cancellation-status">到期后取消</span>';
                }
                
                html += `
                    <div class="card">
                        <div class="card-content">
                            <strong>订阅 #${subscription.id.slice(0, 8)}</strong><br>
                            客户: ${customer ? (customer.name || customer.email) : subscription.customer_id}<br>
                            产品: ${product ? product.name : subscription.product_id}<br>
                            状态: <span class="subscription-status ${statusClass}">${statusDisplay}</span>${cancellationIndicator}<br>
                            当前周期: ${startDate} - ${endDate}<br>
                            创建时间: ${new Date(subscription.created_at).toLocaleString()}
                        </div>
                        <div class="card-actions">
                            <button onclick="showUpgradeModal('${subscription.id}', '${subscription.product_id}')" class="btn btn-secondary">升级/降级</button>
                            <button onclick="cancelSubscription('${subscription.id}')" class="btn btn-danger">取消订阅</button>
                            ${subscription.cancel_at_period_end ? `<button onclick="renewSubscription('${subscription.id}')" class="btn btn-success">续订</button>` : ''}
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 创建订阅
        async function createSubscription(e) {
            e.preventDefault();
            
            const customerId = document.getElementById('subscriptionCustomer').value;
            const productId = document.getElementById('subscriptionProduct').value;
            
            if (!customerId || !productId) {
                showStatus('error', '请选择客户和产品');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/subscriptions`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        customer_id: customerId,
                        product_id: productId
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', `订阅创建成功: ${result.id}`);
                    document.getElementById('subscriptionForm').reset();
                    await loadSubscriptions();
                } else {
                    throw new Error(result.detail || '创建订阅失败');
                }
            } catch (error) {
                console.error('创建订阅失败:', error);
                showStatus('error', `创建订阅失败: ${error.message}`);
            }
        }

        // 创建订阅支付
        async function createSubscriptionWithPayment() {
            const customerId = document.getElementById('subscriptionCustomer').value;
            const productId = document.getElementById('subscriptionProduct').value;
            
            if (!customerId || !productId) {
                showStatus('error', '请选择客户和产品');
                return;
            }
            
            try {
                showStatus('info', '正在创建订阅支付会话...');
                
                const response = await fetch(`${API_BASE_URL}/subscriptions/checkout`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        customer_id: customerId,
                        product_id: productId
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', '订阅支付会话创建成功，正在跳转到支付页面...');
                    // 跳转到Stripe支付页面
                    window.open(result.checkout_url, '_blank');
                    // 清空表单
                    document.getElementById('subscriptionForm').reset();
                } else {
                    throw new Error(result.detail || '创建订阅支付失败');
                }
            } catch (error) {
                console.error('创建订阅支付失败:', error);
                showStatus('error', `创建订阅支付失败: ${error.message}`);
            }
        }

        // 更新客户选择器
        function updateCustomerSelects() {
            const selects = ['subscriptionCustomer', 'portalCustomer'];
            
            selects.forEach(selectId => {
                const select = document.getElementById(selectId);
                if (select) {
                    select.innerHTML = '<option value="">请选择客户</option>';
                    if (customers && customers.length > 0) {
                        customers.forEach(customer => {
                            select.innerHTML += `<option value="${customer.id}">${customer.name || customer.email}</option>`;
                        });
                    }
                }
            });
        }

        // 更新产品选择器
        function updateProductSelects() {
            const select = document.getElementById('subscriptionProduct');
            if (select) {
                select.innerHTML = '<option value="">请选择产品</option>';
                if (products && products.length > 0) {
                    products.forEach(product => {
                        const price = (product.unit_amount / 100).toFixed(2);
                        const interval = product.interval === 'month' ? '月' : '年';
                        select.innerHTML += `<option value="${product.id}">${product.name} - ${price} ${product.currency.toUpperCase()}/${interval}</option>`;
                    });
                }
            }
        }

        // 更新统计信息
        function updateStats() {
            document.getElementById('customerCount').textContent = customers ? customers.length : 0;
            document.getElementById('productCount').textContent = products ? products.length : 0;
            document.getElementById('subscriptionCount').textContent = subscriptions ? subscriptions.length : 0;
        }

        // 打开 Customer Portal
        async function openCustomerPortal() {
            const customerId = document.getElementById('portalCustomer').value;
            
            if (!customerId) {
                showStatus('error', '请选择客户');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/create-portal-session`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        customer_id: customerId,
                        return_url: `${window.location.origin}/portal-return`
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    // 在新窗口打开 Customer Portal
                    window.open(result.url, '_blank');
                    showStatus('success', 'Customer Portal 已在新窗口打开');
                } else {
                    throw new Error(result.detail || '创建 Portal 会话失败');
                }
            } catch (error) {
                console.error('打开 Customer Portal 失败:', error);
                showStatus('error', `打开 Customer Portal 失败: ${error.message}`);
            }
        }

        // 更新统计信息
        function updateStats() {
            document.getElementById('customerCount').textContent = customers.length;
            document.getElementById('productCount').textContent = products.length;
            document.getElementById('subscriptionCount').textContent = subscriptions.length;
        }

        // 升级/降级相关变量
        let currentSubscriptionId = null;
        let currentProductId = null;

        // 显示升级/降级模态框
        function showUpgradeModal(subscriptionId, productId) {
            currentSubscriptionId = subscriptionId;
            currentProductId = productId;
            
            // 填充产品选择器（排除当前产品）
            const upgradeProductSelect = document.getElementById('upgradeProduct');
            upgradeProductSelect.innerHTML = '<option value="">请选择产品</option>';
            
            if (products && products.length > 0) {
                products.forEach(product => {
                    if (product.id !== productId) { // 排除当前产品
                        const price = (product.unit_amount / 100).toFixed(2);
                        const interval = product.interval === 'month' ? '月' : '年';
                        upgradeProductSelect.innerHTML += `<option value="${product.id}">${product.name} - ${price} ${product.currency.toUpperCase()}/${interval}</option>`;
                    }
                });
            }
            
            // 显示模态框
            document.getElementById('upgradeModal').style.display = 'block';
        }

        // 关闭升级/降级模态框
        function closeUpgradeModal() {
            document.getElementById('upgradeModal').style.display = 'none';
            currentSubscriptionId = null;
            currentProductId = null;
        }

        // 处理升级/降级表单提交
        async function handleUpgradeSubmit(e) {
            e.preventDefault();
            
            const newProductId = document.getElementById('upgradeProduct').value;
            const prorationBehavior = document.getElementById('prorationBehavior').value;
            const billingCycleAnchor = document.getElementById('billingCycleAnchor').value;
            
            if (!newProductId) {
                showStatus('error', '请选择新产品');
                return;
            }
            
            try {
                showStatus('info', '正在处理升级/降级请求...');
                
                const response = await fetch(`${API_BASE_URL}/subscriptions/${currentSubscriptionId}/upgrade`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        new_product_id: newProductId,
                        proration_behavior: prorationBehavior,
                        billing_cycle_anchor: billingCycleAnchor
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', '订阅升级/降级成功！');
                    closeUpgradeModal();
                    await loadSubscriptions();
                } else {
                    throw new Error(result.detail || '升级/降级失败');
                }
            } catch (error) {
                console.error('升级/降级失败:', error);
                showStatus('error', `升级/降级失败: ${error.message}`);
            }
        }

        // 取消订阅
        async function cancelSubscription(subscriptionId) {
            if (!confirm('确定要取消这个订阅吗？')) {
                return;
            }
            
            try {
                showStatus('info', '正在取消订阅...');
                
                const response = await fetch(`${API_BASE_URL}/subscriptions/${subscriptionId}?cancel_at_period_end=true`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    showStatus('success', '订阅已取消');
                    await loadSubscriptions();
                } else {
                    const result = await response.json();
                    throw new Error(result.detail || '取消订阅失败');
                }
            } catch (error) {
                console.error('取消订阅失败:', error);
                showStatus('error', `取消订阅失败: ${error.message}`);
            }
        }

        // 续订订阅
        async function renewSubscription(subscriptionId) {
            if (!confirm('确定要续订这个订阅吗？订阅将继续自动续费。')) {
                return;
            }
            
            try {
                showStatus('info', '正在续订订阅...');
                
                const response = await fetch(`${API_BASE_URL}/subscriptions/${subscriptionId}/renew`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus('success', '订阅续订成功！');
                    await loadSubscriptions();
                } else {
                    throw new Error(result.detail || '续订失败');
                }
            } catch (error) {
                console.error('续订失败:', error);
                showStatus('error', `续订失败: ${error.message}`);
            }
        }
    </script>
</body>
</html>

